package com.zaimokuza.cn.config.interceptor;

import com.zaimokuza.cn.entity.constants.ResponseConstant;
import com.zaimokuza.cn.entity.response.ResponseFormat;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 用于处理包装返回值相关逻辑的拦截器
 *
 * @author zaimokuza
 */
public class ResponseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求的方法是否符合要求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取方法的具体信息
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> clazz = handlerMethod.getBeanType();
        Method method = handlerMethod.getMethod();
        // 判断类对象和方法对象上是否加了注解，如果添加了注解，将请求往下传递
        if (clazz.isAnnotationPresent(ResponseFormat.class)) {
            request.setAttribute(ResponseConstant.RESPONSE_FORMAT_MARK, clazz.getAnnotation(ResponseFormat.class));
        } else if (method.isAnnotationPresent(ResponseFormat.class)) {
            request.setAttribute(ResponseConstant.RESPONSE_FORMAT_MARK, method.getAnnotation(ResponseFormat.class));
        }
        //
        return true;
    }

}